<template>
  <div>
    <!-- 面包屑导航区域 -->
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb> -->

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getGoodsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGoodsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="setRoleDialogVisible = true"
            >添加商品</el-button
          >
        </el-col>
      </el-row>

      <!-- table表格区域 -->
      <el-table :data="goodslist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column
          label="商品价格(元)"
          prop="goods_price"
          width="95px"
        ></el-table-column>
        <el-table-column
          label="商品重量"
          prop="goods_weight"
          width="70px"
        ></el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="140px">
          <template slot-scope="scope">
            {{ scope.row.add_time | formatDate1 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.goods_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 添加商品的对话框 -->
    <el-dialog
      title="添加商品"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <!-- 新增商品布局 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
        >
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addForm.goods_price"></el-input>
          </el-form-item>

          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="addForm.goods_number"></el-input>
          </el-form-item>

          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="addForm.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品图片" prop="pics">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品详情" prop="goods_introduce">
            <el-input
              type="textarea"
              :rows="5"
              placeholder="请输入商品详情"
              v-model="addForm.goods_introduce"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addGoodsList">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import { goodslist, delgoods, addgoods } from "@/api/api.js";

export default {
  data() {
    return {
      // 查询参数对象
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      // 商品列表
      goodslist: [],
      // 总数据条数
      total: 0,
      // 添加商品对话框
      setRoleDialogVisible: false,
      // 添加商品表单数据
      addForm: {
        goods_name: "奎哥22",
        goods_price: 10,
        goods_number: 10,
        goods_weight: 10,
        // 商品所属的分类数组
        // goods_cat: [1,3,6],
        goods_cat: [],
        // 图片的数组
        pics: [
          //  {"pic":"/tmp_uploads/30f08d52c551ecb447277eae232304b8"},
          //  {"pic":"/tmp_uploads/30f08d52c551ecb447277eae232304b9"}
        ], //{'pic':'存储上传成功后的临时路径'}
        // 商品的详情描述
        goods_introduce: "",
        attrs: [],
      },
      // 添加商品表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
      },
      // 上传图片的接口地址
      uploadURL: "http://shiyansong.cn:8888/api/private/v1/upload",
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: localStorage.getItem("token"),
      },
      previewPath: "", //预览路径
      previewVisible: false,
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    // 商品列表
    async getGoodsList() {
      const res = await goodslist(this.queryInfo);

      if (res.meta.status === 200) {
        this.$message.success("获取商品列表成功！");
        this.goodslist = res.data.goods;
        this.total = res.data.total;
      }
    },
    //分页操作
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getGoodsList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getGoodsList();
    },
    //删除操作
    async removeById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该商品, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("已经取消删除！");
      }

      const res = await delgoods(id);

      if (res.meta.status === 200) {
        this.$message.success("删除成功！");
        this.getGoodsList();
      }
    },
    
    //添加商品对话框关闭
    setRoleDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 处理图片预览效果
    //1.通过点击时当前文件流信息，获取后台会返回1个正式路径地址，你把此路径写入到图片<img src="后端返回url地址">中即可
    handlePreview(file) {
      console.log(228, file);
      this.previewVisible = true; //预览弹框显示
      let url = file.response.data.url;
      this.previewPath = url;
    },

    // 处理移除图片的操作
    //0.在移除的时候删除的是临时路径 1. 如何获取将要删除的图片的临时路径 ?删除时会响应当前文件信息， 从提交表单图片pics数组中，找到这个图片对应的索引值。从该数组中splice切除掉
    handleRemove(file) {
      // console.log(228,file); //点击这行信息，拿出删除临时路径
      let tpm_path = file.response.data.tmp_path;
      //从数组中把它删除掉  ['a','b'].indexOf('b')
      //findIndex可以遍历,写循环条件查出下标
      let i = this.addForm.pics.findIndex((item) => item.pic == tpm_path); //返回下标
      console.log(235, i);
      this.addForm.pics.splice(i, 1);
    },

    // 监听图片上传成功的事件-response[{pic:临时路径地址}]
    //0.点击上传成功后 ,后台会返回临时路径和正式地址 1. 拼接得到一个图片信息对象 const picInfo = { pic: response.data.tmp_path } ！！注意，因为后端接口需要传pic字段，所以拼接下  2. 将图片信息对象picInfo，push 到表单图片pics数组中
    handleSuccess(res) {
      console.log(230, res); //成功响应有临时路径，还有正式地址
      let picStr = { pic: res.data.tmp_path }; //注意要按照接口里要求的键拼接 {'pic':'上传成功后的临时路径'}
      this.addForm.pics.push(picStr);
    },
    //添加提交商品
    addGoodsList() {
      this.$refs["addFormRef"].validate(async (valid) => {
        //验证通过
        if (valid) {
          //提交接口
          const res = await addgoods(this.addForm);
          console.log("res", res);
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg);
            this.setRoleDialogVisible = false;
          }
        } else {
          this.$message.error("请填写必要的商品信息");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped></style>
